package org.finesys.ai.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.finesys.ai.convert.AigcAppConvert;
import org.finesys.ai.entity.AigcApp;
import org.finesys.ai.entity.AigcAppKnowledge;
import org.finesys.ai.entity.AigcKnowledge;
import org.finesys.ai.entity.AigcModel;
import org.finesys.ai.mapper.AigcAppMapper;
import org.finesys.ai.service.AigcAppKnowledgeService;
import org.finesys.ai.service.AigcAppService;
import org.finesys.ai.service.AigcKnowledgeService;
import org.finesys.ai.service.AigcModelService;
import org.finesys.ai.vo.AigcAppExcelVO;
import org.finesys.common.core.exception.BusinessException;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class AigcAppServiceImpl extends BaseServiceImpl<AigcAppMapper, AigcApp> implements AigcAppService {


    private final AigcAppKnowledgeService aigcAppKnowledgeService;
    private final AigcKnowledgeService knowledgeService;
    private final AigcModelService aigcModelService;

    @Override
    public boolean addApp(AigcApp aigcApp) {
        //是否新增成功
        boolean isAdd = this.save(aigcApp);
        if (!isAdd) {
            return false;
        }
        //模型信息

        //知识库信息
        List<String> knowledgeIds = aigcApp.getKnowledgeIds();
        if (knowledgeIds == null) {
            return true;
        }
        List<AigcAppKnowledge> aigcAppKnowledges = new ArrayList<>(knowledgeIds.size());
        if (knowledgeIds != null && !knowledgeIds.isEmpty()) {
            for (String knowledgeId : knowledgeIds) {
                AigcAppKnowledge aigcAppKnowledge = new AigcAppKnowledge();
                aigcAppKnowledge.setAppId(aigcApp.getId());
                aigcAppKnowledge.setKnowledgeId(knowledgeId);
                aigcAppKnowledges.add(aigcAppKnowledge);
            }
        }
        if (aigcAppKnowledges.size() > 0) {
            isAdd = aigcAppKnowledgeService.saveBatch(aigcAppKnowledges);
        }

        return isAdd;
    }


    @Override
    public boolean updateApp(AigcApp aigcApp) {
        //是否新增成功
        boolean isUpdate = this.updateById(aigcApp);
        if (!isUpdate) {
            return false;
        }
        //模型信息
        //删除原有知识库信息
        aigcAppKnowledgeService.remove(new LambdaQueryWrapper<AigcAppKnowledge>().eq(AigcAppKnowledge::getAppId, aigcApp.getId()));
        //知识库信息
        List<String> knowledgeIds = aigcApp.getKnowledgeIds();
        List<AigcAppKnowledge> aigcAppKnowledges = new ArrayList<>();
        // 校验知识库是否是同纬度
        if (knowledgeIds != null && !knowledgeIds.isEmpty()) {
            List<AigcKnowledge> list = knowledgeService.list(Wrappers.<AigcKnowledge>lambdaQuery().in(AigcKnowledge::getId, knowledgeIds));
            Set<String> modelIds = new HashSet<>();
            Set<String> storeIds = new HashSet<>();
            list.forEach(know -> {
                modelIds.add(know.getEmbedModelId());
                storeIds.add(know.getEmbedStoreId());
                //关联信息
                AigcAppKnowledge aigcAppKnowledge = new AigcAppKnowledge();
                aigcAppKnowledge.setAppId(aigcApp.getId());
                aigcAppKnowledge.setKnowledgeId(know.getId());
                aigcAppKnowledges.add(aigcAppKnowledge);
            });
            if (modelIds.size() > 1) {
                throw new BusinessException("请选择相同向量库数据源配置的知识库");
            }
            if (storeIds.size() > 1) {
                throw new BusinessException("请选择相同向量模型配置的知识库");
            }

        }
        if (aigcAppKnowledges.size() > 0) {
            isUpdate = aigcAppKnowledgeService.saveBatch(aigcAppKnowledges);
        }

        return isUpdate;
    }

    @Override
    public boolean deleteApp(String[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        this.removeByIds(Arrays.asList(ids));
        aigcAppKnowledgeService.remove(new LambdaQueryWrapper<AigcAppKnowledge>().in(AigcAppKnowledge::getAppId, Arrays.asList(ids)));
        return true;
    }

    @Override
    public List<AigcAppExcelVO> listExcel() {
        List<AigcApp> list = baseMapper.selectList(Wrappers.emptyWrapper());
        return AigcAppConvert.INSTANCE.convertList(list);
    }
    @Override
    public List<AigcApp> findList(AigcApp aigcApp){
        List<AigcApp> list = super.findList(aigcApp);
        //获取知识库信息
        Map <String,AigcKnowledge> aigcKnowledgeMap= knowledgeService.list().stream().collect(Collectors.toMap(AigcKnowledge::getId,Function.identity(),(k1,k2)->k1));
        //获取模型信息
        Map <String,AigcModel> aigcModelMap= aigcModelService.list().stream().collect(Collectors.toMap(AigcModel::getId,Function.identity(),(k1,k2)->k1));
        //知识库与应用的关联关系
        Map <String,List<AigcAppKnowledge>> aigcAppKnowledgeMap=  aigcAppKnowledgeService.list().stream().collect(Collectors.groupingBy(AigcAppKnowledge::getAppId));
        //处理模型信息和知识库信息
        list.forEach(app->{
            //模型信息
            if(StringUtils.isNotEmpty(app.getModelId())){
                app.setModel(aigcModelMap.get(app.getModelId()));
            }
            //知识库信息
            if(aigcAppKnowledgeMap.containsKey(app.getId())){
                app.setKnowledgeIds(aigcAppKnowledgeMap.get(app.getId()).stream().map(ap->ap.getKnowledgeId()).collect(Collectors.toList()));
                //知识库取值
                List<AigcKnowledge> aigcKnowledges=new ArrayList<>(app.getKnowledgeIds().size());
                app.getKnowledgeIds().forEach(knowledgeId->{
                    if(aigcKnowledgeMap.containsKey(knowledgeId)){
                      AigcKnowledge aigcKnowledge=  aigcKnowledgeMap.get(knowledgeId);
                      if(!ObjectUtils.isEmpty(aigcKnowledge)){
                          aigcKnowledges.add(aigcKnowledge);
                      }
                    }
                }); 
                app.setKnowledgeList(aigcKnowledges);
            }
        });

        return list;
    }


    /** 根据ID获取信息 */
    @Override
    public AigcApp getById(String id){
        AigcApp aigcApp=super.getById(id);
        //模型信息
        if(StringUtils.isNotEmpty(aigcApp.getModelId())){
            AigcModel aigcModel=aigcModelService.getById(aigcApp.getModelId());
            if(!ObjectUtils.isEmpty(aigcModel)){
                aigcApp.setModel(aigcModel);
            }
        }
        //获取知识库信息
        List<AigcAppKnowledge> appKnowledges=aigcAppKnowledgeService.list(Wrappers.<AigcAppKnowledge>lambdaQuery().eq(AigcAppKnowledge::getAppId, aigcApp.getId()));
        if(appKnowledges!=null&&!appKnowledges.isEmpty()){
            List<String> knowledgeIds=appKnowledges.stream().map(s->s.getKnowledgeId()).collect(Collectors.toList());
            aigcApp.setKnowledgeIds(knowledgeIds);
            //获取知识库信息
            List<AigcKnowledge> knowledgeList=knowledgeService.list(Wrappers.<AigcKnowledge>lambdaQuery().in(AigcKnowledge::getId, knowledgeIds));
            if(knowledgeList!=null&&!knowledgeList.isEmpty()){
                aigcApp.setKnowledgeList(knowledgeList);
            }
        }
        return aigcApp;
    }
}
